AudioStreamPlayer

AudioStreamPlayer plays sound and music

The AudioStreamPlayer node is your one-stop to play all audio and music in your Godot games.

Godot 3.4 supports three audio file formats: WAV, OGG (Vorbis), and MP3.

WAV files store uncompressed audio. The computer can load and process uncompressed audio quickly at the cost of larger file sizes.

OGG and MP3 are lossy, compressed formats. Lossy file sizes are much smaller at the cost of losing audio quality and taking a bit longer to load and play.

AudioStreamPlayer has two positional variants: AudioStreamPlayer2D and AudioStreamPlayer3D. The position of these two nodes changes the volume, direction, and clarity of sound relative to the game’s camera. This helps give more realistic audio results for players.

In this guide, you will learn how to:

Contents:

AudioStreamPlayer’s key features

The AudioStreamPlayer node comes with support for many audio resource types. This node works in tandem with Godot’s audio mixer tracks to give you a lot of control over the sounds in your game.

You can use AudioStreamPlayer with Area2D and Area nodes to play ambient sounds or apply effects only in a given area.

While the node is versatile, most of the time, you only need a handful of key properties:

Playing one-shot and looping sounds

To play a sound with an AudioStreamPlayer:

  1. Create an AudioStreamPlayer node.
  2. Drag-and-drop an audio file onto its Stream property.
  3. From code, call the node’s play() method.

To make the sound loop, you need to change its import properties:

  1. Select the audio file you want to loop in the FileSystem dock.
  2. Head to the Import dock and turn on the Loop checkbox.
  3. Click the Reimport button.

You can select multiple audio files (for example, your game’s entire soundtrack) at once and set them all to loop using the steps above.

Controlling playback

You can play, pause and stop an AudioStreamPlayer’s playback using three properties and methods:

Lastly, you can turn on the Autoplay property to automatically play music when adding the node to the scene.

In the editor, you can preview the sound in a few places:

  1. You can click the checkbox next to the Playing property to play the sound from the start.
  2. If you click the Stream resource, an audio player appears at the bottom of the Inspector.

There, you can click anywhere on the audio waveform to seek to a different time, click the play icon to play from the blue marker’s position, and click the stop icon to stop playback.

Adjust the volume of multiple audio sources using buses

You can find the mixer’s interface in the Audio bottom panel.

It displays a row of buses: channels through which multiple audio streams travel before the player hears the sound.

By default, there is only one Master bus through which all game audio flows. You can see at the bottom of its column that it outputs sound to the players’ speakers.

The vertical slider in each bus controls the volume of all sound passing through it. You can animate this value using a Tween node to fade audio in and out.

This property also allows you to expose volume sliders to your players:

To create a new bus, click the Add Bus button in the top-right of the Audio panel.

In the setup shown below, every audio bus flows toward the master bus. The master bus always outputs the audio to the speakers.

For the AudioStreamPlayer node itself, you can send audio to a specific bus using the Bus property.

As a way to get started with audio on a project, we recommend creating two buses: one for music, another for sound effects. New AudioStreamPlayer nodes can have their bus assigned to either. You can then customize the volume of music and sounds separately. Also, you can apply reverb only to in-game sounds.

Applying effects to your sounds with the audio mixer

Godot offers a mixer with real-time effects you can apply to any audio source.

You can click the Add Effect button inside any bus to display the complete list of available effects. These effects process the sound in real-time, so mind that they have some performance cost.

However, we often recommend using real-time sound effects over baking them into your audio files. This saves file size and offers more flexibility.

Here’s a quick look at the most common effects:

There are many more effects to learn about and experiment with. Once you hear how each effect modifies the sound, you can start to understand when and where you want to use them.

As with almost everything in Godot, remember you can animate the effects and their properties using a Tween. This is key to creating believable sound transitions, like when a character goes underwater.

Unfortunately, you currently cannot animate properties from the audio mixer with an AnimationPlayer.

You can see the complete list of audio effects in the official documentation: Adding effects to audio buses.

How to use an AudioStreamPlayer in practice

Let’s now talk about how to use the node in practice.

We start by building upon the key features we learned above to play individual sounds and music. We then move to more and more elaborate examples that require multiple sounds.

Playing positional sound effects

To play sounds that always play at the same volume regardless of their position in the scene, you want to add AudioStreamPlayer nodes to the scenes that should play it. If you want a character to play footsteps, you can attach the footstep sound to the player scene.

And for a weapon to play a firing sound, you can attach the firing sound to the weapon.

For sounds that pan and fade depending on their position in the world, you can use an AudioStreamPlayer2D instead of a plain AudioStreamPlayer. The farther away the sound is from the camera, the less you’ll hear the sound.

It also gives you a nice stereo effect: if the node is to the left of the camera, you hear it most in the left speaker. If it’s on the right, you hear it from the right speaker.

To play the sound from GDScript, you can get a reference to the node and call its play() method.

onready var _stream_player := $AudioStreamPlayer2D

func fire() -> void:
    # ...
    _stream_player.play()

Alternatively, you can use an AnimationPlayer with an Audio Playback Track.

You can create one by clicking Add Track in the Animation bottom panel.

To add a sound to audio tracks, click and drag the audio file onto it.

To learn more about using the AnimationPlayer node, check out our dedicated guide: AnimationPlayer.

Playing and pausing music

This example shows how to play music and pause or unpause it by toggling a button.

We use a check button as it works as a toggle by default. While it normally looks like a radio button, you can give it any look you want using its theme properties.

We used two sprites to make it look like a play button.

By connecting to the button’s toggled signal, we can pause and unpause the music.

Note: The stream_pause property only updates when the audio starts or stops. If the sound is not playing, setting this property to false does not start playback. You must use the play() method or set the playing to true to do so:

onready var _audio_player := $AudioStreamPlayer
onready var _button := $CheckButton


func _ready() -> void:
    _button.connect("toggled", self, "toggle_playback")


func toggle_playback(do_play: bool) -> void:
    # We can check if the soundtrack is playing with the `playing` property.
    # We need that for the stream_pause property to have an effect.
    if not _audio_player.playing:
        _audio_player.play()
    # This property pauses the stream. It only has an effect if the audio is playing.
    _audio_player.stream_paused = not do_play

Playing voice-overs for game dialogues

You can use audio playback animation tracks to play voice-overs for your game dialogues.

Using Godot’s animation system gives you fine control over how the text appears and when exactly the voice-overs play.

In this demo, we are just playing animations for each line of dialogue.

This approach can be especially useful for games with heavily animated text like Katana Zero that cue up to match the audio:

The more voice-overs there are to animate, the more a procedural approach might help save time.

Randomizing sounds

If you play one audio file over and over for a common action, like footsteps, most players notice the artificial repetition of the sound, breaking their immersion.

Repetitive sounds often sound better if they vary slightly. You’ll want to consider randomizing sounds that get played often without much time between their playback, like a weapon firing or your character’s jump.

We can shuffle and randomize the playback of our audio files to make the game sound more believable.

Here are the two most common ways in which you can do that in Godot:

  1. Playing a random sound from a list of files. You store multiple sounds in an array and play one randomly using GDScript.
  2. Shifting the audio’s pitch on every playback. Godot can shift the pitch of your audio samples just enough to add variation and flavor to your game sounds.

You can combine those two techniques to add even more variety to the sounds.

Playing random sounds from an array

To randomize sounds played on an AudioStreamPlayer, we need a script. We can export an array of sound resources to set them in the Inspector.

extends AudioStreamPlayer

# Using the export hint in parentheses, we tell Godot to create an array that
# only accepts audio streams.
export (Array, AudioStream) var effects_list


## Overrides the play() method to play a random sound from an array.
func play(from_position: float = 0.0) -> void:
    # We calculate a random index and select the corresponding sound from the
    # `effects_list` array.
    var index: int = randi() % effects_list.size()
    stream = effects_list[index]
    # As we override the method, we use the dot notation to call play() in the
    # parent class.
    .play(from_position)

Doing things with a script allows us to reuse the same script anywhere in our game project.

You can also give the script a class_name to directly create nodes with that feature from the Create New Node window.

Randomizing the pitch on every playback

Godot can randomize the pitch of your sound automatically on playback. The feature comes built into the AudioStreamRandomPitch resources.

Instead of directly dragging and dropping audio files into the Inspector, you want to right-click on the Stream property and create an AudioStreamRandomPitch.

Expand the resource and set the Randomized Pitch property to randomize the pitch on each playback.

Changing the sound based on the environment

You’ll often want to change how audio plays depending on where the player is. If they go underwater, you can muffle the high frequencies of all sound effects.

If they enter a church or a cavern, you might want steps and other sounds to reverberate, as they do in the real world.

To do so, you can use an Area node in combination with audio buses.

While Area nodes are usually linked to physics, they also let you route audio streams through different mixer channels.

In turn, audio buses allow you to apply a wide variety of audio effects in real-time.

In this demo, we created an Area2D to represent water and a new audio bus named Water using the Audio bottom panel.

The Water audio bus has both a low-pass and a reverb effect: they respectively attenuate the sound and make the space the character is in feel floaty.

To achieve this result, we use a low value for the low-pass filter’s cut-off frequency: 540 Hz. This means the filter cuts all sounds with medium and high pitches.

For the reverb, the only change to the default settings is a lower Room Size to avoid expanding the sound too much.

By turning on the area’s Audio Bus -> Enable property and setting the Audio Bus -> Name to Water, whenever the player’s character enters the area, any positional sound attached to it automatically changes.

Note this doesn’t work with AudioStreamPlayer, it has to be an AudioStreamPlayer2D for the Area2D to detect when it enters and leaves.

The 3D engine supports this same feature with the Area node and AudioStreamPlayer3D.

Using multiple sounds to create a charging laser effect

You often need to combine multiple sounds to create dynamic, believable sounds from longer actions. Charging effects are a canonical example of that, as they typically require two or more audio files:

  1. A long or looping sound while charging.
  2. A firing sound effect when unleashing the charged spell or attack.

You can also use an extra sound at the start to kick off the effect.

In this example, we went with a fixed charging time and a corresponding animation, although you could choose to play a looping sound from code for the charge duration then change the Stream upon firing.

Here is the complete animation for the laser’s charge.

At the top of the window, you can see we use the animation player to call functions.

Using the AnimationPlayer gives us a lot of control over the charge’s timing. If the player releases the charge before firing, we can stop the animation and particle emission to cancel the attack.

Here’s the scene structure. You can see we use an AudioStreamPlayer2D for sound playback.

Recording in-game sounds

Say you want to create a musical game where the player can record virtual instruments. Or perhaps you want to create a musical puzzle where the player records a tune, and you play it back to them in the same way.

In those cases, you have the option to record in-game audio.

To do so, you have to funnel the audio through a bus with the Record effect.

The engine takes care of all the technical details. In a script, all you have to do to record audio is:

  1. Store a reference to the Record audio effect.
  2. Make the recording active to start recording audio with set_recording_active().
  3. When the recording is done, stop recording.
# We first get the bus with the recording effect and grab a reference to the
# effect from it.
var _record_bus := AudioServer.get_bus_index("Record")
var _effect: AudioEffectRecord = AudioServer.get_bus_effect(_record_bus, 0)
var _recording: AudioStreamSample

# This is a reference to the AudioStreamPlayer we use to listen to our
# recording.
onready var _audio_player: AudioStreamPlayer = $AudioStreamPlayer

func toggle_recording(do_record: bool) -> void:
    # Before toggling the recording off, we store the recorded stream to play it
    # back later.
    if _effect.is_recording_active():
        _recording = _effect.get_recording()
    # We use the following method to turn recording on and off.
    _effect.set_recording_active(do_record)

func play_recording() -> void:
    # To listen to the recorded track, we assign the recording to our
    # AudioStreamPlayer and play like usual.
    _audio_player.stream = _recording
    _audio_player.play()

You can grab the recorded Stream with the _effect.get_recording() method, assign it to an AudioStreamPlayer, and play it like any other audio file.

Recording the player’s microphone

Just like recording game sounds, you can also record audio from the player’s microphone.

In theory, Godot supports this feature on Windows, Mac OS, Linux, Android, and iOS.

Unfortunately, it currently does not work on some Linux distributions with official stable builds in Godot 3.3. See this issue for more information: Microphone recording doesn’t work on Linux with official builds.

The way this works is a little confusing as you do not explicitly have a function to record from the microphone.

Instead, you start with the same setup as recording game audio: a bus with a Record effect. The difference is you need an extra AudioStreamPlayer with an AudioStreamMicrophone resource as its Stream.

Also, you must set its Bus property to the bus with the Record audio effect.

This is all it takes: once you set the recording to be active, the AudioStreamMicrophone resource kicks in and record audio from the player.

Note that you cannot access the microphone on mobile platforms without first getting permission from the user.

Adding sound to 3D objects

Games in 3D space benefit hugely from positional audio. In first-person shooters, the stereo information can tell the player a lot about the locations of enemies. It’s important for tactical reasons, and it enriches your digital world.

We are adding audio to a radio the player can carry around. The carrying drags the object using forces, which gives you a strong stereo experience as the radio moves around the player.

We use a RayCast to detect the objects in front of the player. We use a remote transform to save a reference to the object when the player clicks. Next, in the _process() function we apply a force to the object towards a point in front of the player.

We add an AudioStreamPlayer3D, with an audio stream to the origin of our radio. We adjust the Unit Db until we are happy with the volume. By playing the sound, we can test the volume without starting our game.

We start playing our audio in a function called activate(), which we call when the player picks up the object.

func play(is_playing: bool) -> void:
    if _audio_player.playing and is_playing:
        return
    _audio_player.play() if is_playing else _audio_player.stop()

Stereo audio in 3D

3D games are excellent at providing a realistic stereo sound that takes your position into account. We can have sounds that are louder in one ear than the other depending on volume and proximity. We can also have sounds emitting at specific angles, cutting their frequencies to give complex attenuation with little work.

To demonstrate this, we have set up a stage with stereo-directional audio.

All the setup is possible from within the Inspector:

We need an AudioStreamPlayer3D with a set Audio Stream. Then, we can increase the volume and distance the audio covers by increasing the Unit Db and Unit Size properties.

The properties for controlling volume over distance can be hard to wrangle into the sound you want:

Finally, set the Emission Angle property: check Enabled to produce the audio in a 45-degree cone.

You can see the direction of the Cone in the 3D viewport. Adjust its rotation until you are pointing it in the desired direction.

Be sure to try out the demo where you can walk around the stage and notice how the audio changes when you are behind the speaker or very close to one.

Listening to 3D audio through a security camera

There are many circumstances where you would want to change your game’s active Camera to a new position, be it to play a cutscene, focus your player on objectives, or remotely view a location.

Thankfully, when you change your view, the sound automatically updates to use the position of the active Camera!

By default, all positional audio has its volume and attenuation calculated from the position of the current Camera. If you want this position to be different, you can use a Listener node.

Always using the position for the current Camera makes it all the more important to understand how the AudioStreamPlayer3D and its properties affect volume with distance — its attenuation.

We are taking advantage of these properties to make two rooms with separate positional audio: one viewed in the first person, and the other through a security camera.

We have two AudioStreamPlayer3D nodes in the room with the security console to give an even spread of sound throughout the room, playing idle humming.

The Unit Size property for these nodes determines how quickly volume decreases with distance. The Attenuation property controls the shape of how the sound drops off with distance.

In this property, you choose between the audio decreasing:

You can see their definitions in the official documentation.

Keeping this Inverse is fine for our case, but they are worth experimenting with, especially if you want a sound to be more uniform in an area InverseSquare and Log are helpful.

The Max Distance property handles the maximum range at which a sound is audible. When beyond the Max Distance, audio is either paused or mixed so quiet it’s inaudible.

We set the Maximum range to 10 as our rooms are 20 units apart, so they are safe from their audio overlapping.

The second room is an inverted CSGBox, with a camera inside, panning with an AnimationPlayer. The center of this room has an identical AudioStreamPlayer3D to the first room with a unique Audio Stream.

Simply setting the Camera in the second room as current is enough to make the audio update to the new location, all built-in!

export var security_camera_nodepath: NodePath

onready var _security_camera: Camera = get_node(security_camera_nodepath)
onready var _crt_animator: AnimationPlayer = $TiltPivot/Camera/CanvasLayer/AnimationPlayer
onready var _interaction_timer: Timer = $InteractionTimer
onready var _camera: Camera = $TiltPivot/Camera
func view_through_security_camera() -> void:
    if not _interaction_timer.is_stopped():
        return

    _crt_animator.play("SwapToSecurityCamera")
    _security_camera.current = true


func reset_to_player_camera() -> void:
    _crt_animator.play("RESET")
    _camera.current = true
    _interaction_timer.start()

The Doppler effect

The Doppler effect occurs with sounds from fast-moving objects, be it a police siren traveling past, a racecar, or a magical fireball coming at you.

The cause is sound reaches you quicker if an object is coming towards you and slower if it’s going away.

For more real-world examples, the Wikipedia page is a fine source.

Godot supports this audio effect by default, which allows you to create projectiles that give you a much more accurate audio profile of where they are around you.

We only need two steps to apply this audio effect. Enable doppler tracking for the Camera on the idle or physics frame and do the same for the AudioStreamPlayer3D.

We added a monotonous sound with this tracking to a projectile fired at the player. Try dodging the projectiles in the demo scene and listen to the tone as the projectile approaches and continues past you.

Your questions

Which file format should I use? WAV, OGG, or MP3?

WAV files contain uncompressed audio, while OGG and MP3 files store compressed audio streams.

As a result, WAV files are large for the same duration but load and process fast, while OGG and MP3 files are much smaller but have a higher CPU performance cost.

We use them like this in games:

Which compressed format should I use: OGG or MP3?

OGG Vorbis produces files with smaller sizes than MP3, but it uses more processing power.

Most of the time, we recommend using OGG to take advantage of the really strong compression. The performance difference is not a big issue on computers and modern phones.

On old mobile devices or in the browser, you may want to use MP3 instead. When exporting your game to the browser, the access to the computer’s CPU is limited, so you might need that to get every ounce of performance out of your game.